import React, { useState, useEffect } from 'react';
import { Input, Button, Dialog, Toast } from 'antd-mobile';
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import styles from './Login.module.css'

const Login = () => {
  const navigate = useNavigate();
  const [studentId, setstudentId] = useState('');
  const [password, setPassword] = useState('');
  const [checked, setChecked] = useState(false);
  const [rememberMe, setRememberMe] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [isPasswordVisible, setIsPasswordVisible] = useState(false);

  // 组件加载时检查是否有保存的账号密码
  useEffect(() => {
    const savedCredentials = localStorage.getItem('userCredentials');
    if (savedCredentials) {
      const { studentId: savedStudentId, password: savedPassword } = JSON.parse(savedCredentials);
      setstudentId(savedStudentId);
      setPassword(savedPassword);
      setRememberMe(true);
    }
  }, []);

  const handleLogin = async () => {
    if (!checked) {
      const result = await Dialog.confirm({
        content: '请先同意用户协议和隐私政策',
        confirmText: '同意',
        cancelText: '取消',
      });
      if (result) {
        setChecked(true);
      }
      return;
    }

    if (!studentId || !password) {
      setError('请输入学号和密码');
      return;
    }

    try {
      setLoading(true);
      // 替换为实际的登录API
      const res = await axios.post('/lz/login', {
        studentId,
        password
      });

      if (res.data.code === 200) {
        console.log(res.data.data);
        // 如果勾选了记住我，保存账号密码
        if (rememberMe) {
          localStorage.setItem('userCredentials', JSON.stringify({ studentId, password }));
        } else {
          // 如果没有勾选记住我，清除保存的账号密码
          localStorage.removeItem('userCredentials');
        }

        Toast.show({
          content: '登录成功',
          icon: 'success',
        });
        localStorage.setItem('token', JSON.stringify(res.data.data));
        // 登录成功处理
        navigate('/');
      } else {
        Toast.show({
          content: res.data.message || '登录失败',
          icon: 'fail',
        });
        setError(res.data.message || '登录失败');
      }
    } catch (err) {
      Toast.show({
        content: '网络错误，请稍后重试',
        icon: 'fail',
      });
      setError('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.login_container}>
      <div className={styles.background_image}></div>

      <div className={styles.login_form}>
        <h2 className={styles.form_title}>用户登录</h2>

        <Input
          placeholder="请输入学号"
          value={studentId}
          onChange={setstudentId}
          className={styles.input_field}
          clearable
        />

        <div className={styles.password_container}>
          <Input
            placeholder="请输入密码"
            type={isPasswordVisible ? 'text' : 'password'}
            value={password}
            onChange={setPassword}
            className={styles.input_field}
          />
          <div 
            className={styles.password_icon}
            onClick={() => setIsPasswordVisible(!isPasswordVisible)}
          >
            {isPasswordVisible ? <EyeOutline /> : <EyeInvisibleOutline />}
          </div>
        </div>

        {/* {error && <div className="error-message">{error}</div>} */}

        <div className={styles.form_actions}>
          <label className={styles.remember_me}>
            <input 
              type="checkbox"
              checked={rememberMe}
              onChange={(e) => setRememberMe(e.target.checked)}
            />
            记住我
          </label>

          <span
            className={styles.forget_password}
            onClick={() => navigate('/forget')}
          >
            忘记密码？
          </span>
        </div>

        <div className={styles.privacy_agreement}>
          <input
            type="checkbox"
            checked={checked}
            onChange={(e) => setChecked(e.target.checked)}
            className={styles.agreement_checkbox}
          />
          我已知晓
          <a href="/agreement" className={styles.agreement_link}>《用户协议》</a>
          和
          <a href="/privacy" className={styles.agreement_link}>《隐私政策》</a>
          ，并同意相关条款
        </div>

        <Button
          block
          color="primary"
          onClick={handleLogin}
          loading={loading}
          disabled={loading}
          className={styles.submit_button}
        >
          登录
        </Button>
      </div>
    </div>
  );
};

export default Login;